package com.cosina.game.colorball;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

public class BallGameView extends View {

	private int maring = 5,
				xCount = 14, 
				yCount = 17, 
				startPointX = 6, 
				startPointY = 6 + BallView.size * 2;

	private BallGame game;
	private long lastEventTime = 0;
	
	public BallGameView(Context context,Difficulty difficulty) {
		super(context);
		game = new BallGame(xCount,yCount,difficulty);
		
	}
	
	protected void onDraw(Canvas canvas) {
		{
			Paint paint = new Paint();
			paint.setColor(Color.WHITE);
			canvas.drawRect(maring, maring, getWidth() - maring, getHeight() - maring, paint);
		}
		{
			Paint paint = new Paint();
			paint.setColor(Color.BLACK);
			paint.setTextSize(24);
			String str = "Total Score " + game.getScore();
			canvas.drawText(str, maring, startPointY/2+9 , paint);
		}

		Paint ballPaint = new Paint();
		for (int y = 0; y < yCount; y++) {
			for (int x = 0; x < xCount; x++) {
				Bitmap pic = game.getBall(x, y).getDrawingPic();
				if(null != pic)
					canvas.drawBitmap(pic,
						startPointX + x * BallView.size, startPointY + y * BallView.size,
						ballPaint);
			}
		}
	}


	@Override
	public boolean onTouchEvent(MotionEvent event) {
		long thisEventTime = event.getEventTime();
		long internal = thisEventTime - lastEventTime;
		if(internal < 250)
			return true;
		
		int xBallIndex = (int)((event.getX() - startPointX)/BallView.size);
		int yBallIndex = (int)((event.getY() - startPointY)/BallView.size);
		
		if(xBallIndex >= xCount || xBallIndex< 0 || yBallIndex >= yCount || yBallIndex < 0)
			return true;
		
		boolean someOneDied = game.diagnosis(xBallIndex, yBallIndex);
		if(someOneDied){
			this.invalidate();
			lastEventTime = thisEventTime;
			if(game.checkNoInfectPossiable()){
				GameEndDialog.show(game.getScore(), getContext());
			}
		}
		 
		return true;
	}
}
